<?php
namespace app\mp\controller;
use think\Controller;
use think\Request;
use think\config;
use think\Db;
use think\Url;
use think\Cache;
 
header("Content-type: text/html; charset=utf-8"); 
define("TOKEN","LPCHvZ3AhyiUOTmcUJBq4h5");//定义识别码 
class Index extends Controller{

    public function index(){

        if(!isset($_GET["echostr"])){ 
            $this->responseMsg(); 
        }
    }
    public function checkToken()
    {

        //1.将timestamp,nonce,toke按字典顺序排序
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $token = 'LPCHvZ3AhyiUOTmcUJBq4h5';
        $signature = $_GET['signature'];
        $array = array($timestamp,$nonce,$token);
        //2.将排序后的三个参数拼接之后用sha1加密
        $tmpstr = implode('',$array);
        $tmpstr = sha1($tmpstr);
        //3.将加密后的字符串与signature进行对比，判断该请求是否来自微信
        if($tmpstr == $signature){
            // echo $_GET['echostr'];
            $this->responseMsg(); 
            exit;
        }
    }
 
    public function responseMsg(){
        db('Driver')->select();
        //get post data, May be due to the different environments
        $postStr = file_get_contents('php://input');
        //extract post data
        if (!empty($postStr)){
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $RX_TYPE = trim($postObj->MsgType);
 
                switch($RX_TYPE){
                    //当回复公众号图片时
                    case "image":
                        // $resultStr = $this->handleImage($postObj);
                        break;
                    //当回复公众号关键字时
                    case "text":
                        // $resultStr = $this->handleText($postObj);
                        break;
                    //关注公众号事件
                    case "event":
                        $resultStr = $this->handleEvent($postObj);
                        break;
                    default:
                        $resultStr = "Unknow msg type: ".$RX_TYPE;
                        break;
                }
                echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }
 
    //回复图片消息
    private function handleImage($object)
    {
        $img_list = Db::name("article")->where("pass",'yes')->order('px asc')->limit(8)->select();
 
        $content = array();
        if(isset($img_list) && !empty($img_list)){
            foreach($img_list as $key=>$item){
                $content[] = array(
                        "Title"=>$item['article_name'], 
                        "Description"=>$item['article_desc'], 
                        "PicUrl"=>"http://域名/".$item['article_img'], 
                        "Url" =>"http://域名/".Url::build('home/article/index',"id=".$item['id'])
                    );
            }
        }
 
        $itemTpl = "<item>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
        </item>";
        $item_str = "";
        //多图文回复
        foreach ($content as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[news]]></MsgType>
            <ArticleCount>%s</ArticleCount>
            <Articles>$item_str</Articles>
        </xml>";
 
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($content));
        return $result;
    }
 
    public function handleText($postObj)
    {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";             
        if(!empty( $keyword )){
            $msgType = "text";
            if($keyword == '1'){
                $contentStr = '关键字回复1';
            }elseif($keyword == '2'){
                $contentStr = '关键字回复2';
            }
 
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        }
    }
    
    // 关注？
    public function handleEvent($object){
        $contentStr = "";
        $keyArray = explode("_", $object->EventKey);
        $EventKey = $object->EventKey;
        $FromUserName = $object->FromUserName;
        $key_count = count($keyArray);

        $data = [
                    'openid' => $object->Event
                ];
                db('WechatUsers')->insert($data);
      
        switch ($object->Event){
            //首次关注
            case "subscribe":
                
                $user = $this->getUserInfo($_GET['openid']);
                $data = [
                    'openid' => $_GET['openid'],
                    'unionid' => $user['unionid']
                ];
                db('WechatUsers')->insert($data);

                $contentStr = '欢迎关注';
            break;
            //已关注
            case "SCAN":
                $contentStr = "再次扫码？";
            break;
            default :
        }
 
        $resultStr = $this->responseText($object, $contentStr);
        return $resultStr;
    }
    
    public function responseText($object, $content, $flag=0)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }
 
    //微信验证
    public function valid(){ 
        $echoStr = $_GET["echostr"]; 
        if($this->checkSignature()){ 
         echo $echoStr; 
         exit; 
        } 
    } 
 
    //检查微信签名
    private function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];    
                
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    // 通过openid获取unionid
    public function getUserInfo($openid)
    {
        // Cache::rm('token');
        // $openid = 'op6vDwIrW-JTRCyRNDCcsLetc8ew';
        //注意，这里请求有次数限制，请做好判断(获取access_token)
        if (!Cache::get('token')) {
            $appid = config('wechat.appid');
            // $appid = 'wx17a8f2e05e5df640';
            $secret = config('wechat.appsecret');
            // $secret = '77924030088bb0696ab6dc6498784a62';
            //第一步:取全局access_token
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $token = getJson($url);
            // var_dump($url);die;
            Cache::set('token', $token["access_token"], 7000);
        }
        $access_token = Cache::get('token');        
        
        //url地址
        $url1 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
        // $url1 = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=$access_token";
        
        return getJson($url1);
    }

    public function getUsersInfo()
    {
        //注意，这里请求有次数限制，请做好判断(获取access_token)
        if (!Cache::get('token')) {
            $appid = config('wechat.appid');
            // $appid = 'wx17a8f2e05e5df640';
            $secret = config('wechat.appsecret');
            // $secret = '77924030088bb0696ab6dc6498784a62';
            //第一步:取全局access_token
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $token = getJson($url);
            // var_dump($url);die;
            Cache::set('token', $token["access_token"], 7000);
        }
        $access_token = Cache::get('token'); 

        $openid = [];   
        $openid['user_list'][] = [
            "openid" => "op6vDwCgjrN1IDKFUoKx_8eYPJF8", 
            "lang" => "zh_CN"
        ];      
        $openid['user_list'][] = [
            "openid" => "op6vDwBAnFpM_gScNG2s3JIfYBM8", 
            "lang" => "zh_CN"
        ];    
        $data = json_encode($openid);

        //url地址
        $url1 = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=$access_token";
        
        $res = http_request($url1, $data);

        var_dump(json_decode($res,true));
    }

    // 创建菜单
    public function createMenu(){

        //注意，这里请求有次数限制，请做好判断(获取access_token)
        if (!Cache::get('token')) {
            $appid = config('wechat.appid');
            // $appid = 'wx17a8f2e05e5df640';
            $secret = config('wechat.appsecret');
            // $secret = '77924030088bb0696ab6dc6498784a62';
            //第一步:取全局access_token
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $token = getJson($url);
            // var_dump($url);die;
            Cache::set('token', $token["access_token"], 7000);
        }
        $access_token = Cache::get('token');        
        
        //url地址
        $url1 = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$access_token";
        //菜单内容
        $data = '{
            "button": [{
                "type":"miniprogram",
                "name":"学习培训",
                "url":"http://mp.weixin.qq.com",
                "appid":"wxe59aec661b6257a7",
                "pagepath":"pages/index/index"
            }]
        }';
        return http_request($url1, $data);

    }
}
 
?>